<template>
	<view class="u-page fullpage" :style="skin">
		<view class="top-warp">
			<zx-nav title="购物车" bg="#fff" fixedTop noHoldHeight noBack>
				<view slot="left" @tap="isEdit = !isEdit">{{ isEdit ? '完成' : '编辑' }}</view>
			</zx-nav>
		</view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :top="topH" :bottom="coupon_deduction.status == 1 ? 80 : 0" @down="downCallback" @up="upCallback" :up="upOption">
			<!-- 数据列表 -->
			<view class="main">
				<view class="card content">
					<!-- <view class="text-primary" style="font-size:26upx;font-weight:500">报价已包含打包材料费，冰袋等，无其他杂项收费</view>
					<view>鲜花到店价=花价+运费(不满10公斤需加收8元包装费)</view>
					<view>
						满
						<text class="text-primary">20kg</text>
						可选冷链专线或其他物流，运输费用较低且损耗小
					</view> -->
					<rich-text :nodes="sysInfo.home_set.shop_info"></rich-text>
				</view>
				<view><cart-item class="mt20 u-block" :list="cartList" @changeAll="changeShopAll" @changeOne="changeShopOne" @changeNum="changCart"></cart-item></view>
				<view v-if="invalidCart && invalidCart.length > 0"><invalid-cart-item class="mt20 u-block" :list="invalidCart" @banchDel="banchDel(0)"></invalid-cart-item></view>
			</view>
		</mescroll-body>
		<view class="carbar u-bg-white" v-if="cartList.length > 0">
			<view class="tip flex justify-between align-center" v-if="coupon_deduction.status == 1">
				<text>
					<text v-if="reduceMoney > 0">已减{{ reduceMoney }}元！</text>
					<text v-if="needMoreNum > 0">
						再购买
						<text class="text-orange">{{ needMoreNum }}</text>
						{{ coupon_deduction.type == 1 ? '元' : '扎' }}，可优惠
						<text class="text-red">{{ couponMoney }}</text>
						元
					</text>
				</text>
				<navigator url="/pages/classify/classify" open-type="switchTab" class="price" v-if="needMoreNum > 0">
					去加购
					<text class="cuIcon-right"></text>
				</navigator>
			</view>
			<view class="paybar flex justify-between align-center">
				<mycheckbox text="全选" @handChange="selectedAll" :state="checkAll"></mycheckbox>
				<view class="flex-sub text-right">
					<template v-if="!isEdit">
						合计：
						<span class="price">
							<text class="unit">￥</text>
							<text>{{ payMoney }}</text>
						</span>
					</template>
				</view>
				<u-button v-if="isEdit" type="info" shape="circle" :disabled="totalNum <= 0" :plain="true" :loading="btnLoading" @tap="banchDel(1)">
					<text style="color: #333">删除</text>
				</u-button>
				<u-button v-else @click="toOrder" :disabled="totalNum <= 0" type="success" shape="circle" :loading="btnLoading">去下单</u-button>
			</view>
		</view>
		<u-modal :show="showModal" @confirm="confirmOrder" @cancel="showModal = false" :showCancelButton="true">
			<view class="slot-content">
				<!-- <p class="mt10">1，下单后平台将进入备货状态，下单10分钟后，不支持退款服务。请谨慎下单。</p>
				<p class="mt10">2，下单时，因无法精确计算产品的重量。包装费用和运输费用为预收规则，您支付的“预收费用”将会在发货后进行多退少补。</p>
				<p class="mt10" style="color: #f00;">客户一经下单，我司即视为已经认真阅读并同意我们的所有售前售后条款。</p>
			 -->
				<rich-text :nodes="sysInfo.home_set.tc_info"></rich-text>
			</view>
		</u-modal>
	</view>
</template>

<script>
import cartItem from './components/cart-item';
import invalidCartItem from './components/invalid-cart-item';
import mycheckbox from '@/components/mycheckbox';
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
import { mapState, mapMutations, mapActions } from 'vuex';
export default {
	data() {
		return {
			btnLoading: false,
			isEdit: false,
			cartList: [],
			invalidCart: [],
			upOption: {
				empty: {
					use: true, // 是否显示空布局
					icon: '/static/mescroll/noCart.png',
					tip: '购物车空空如也～' // 空提示
				}
			},
			isInit: false,
			ids: '',
			showModal: false
		};
	},
	mixins: [MescrollMixin],
	components: { cartItem, mycheckbox, invalidCartItem },
	onShow() {
		if (this.isInit) {
			this.upCallback();
		}
	},
	computed: {
		...mapState(['CustomBar', 'isLogin', 'cartNum', 'sysInfo', 'coupon_deduction']),
		topH() {
			return this.CustomBar + +uni.upx2px(20) + 'px';
		},
		checkAll() {
			return this.cartList.length > 0 ? this.cartList.every(item => item.checked) : false;
		},
		totalPrice() {
			let totalPrice = 0;
			if (!this.isEdit) {
				this.cartList.forEach(shop => {
					shop.data.forEach(good => {
						good.checked ? (totalPrice += good.qty * good.price) : (totalPrice += 0);
					});
				});
			}
			console.log('totalPrice', totalPrice);
			return totalPrice.toFixed(2);
		},
		totalNum() {
			return this.cartList.length > 0 ? this.cartList.filter(item => item.checked).length : 0;
		},
		totalGoodsNum() {
			if (this.cartList.length > 0) {
				let num = this.cartList
					.filter(item => item.checked)
					.reduce((total, item) => {
						let subtotal = item.data.reduce((subtotal, subitem) => {
							return subtotal + subitem.qty;
						}, 0);

						return total + subtotal;
					}, 0);
				console.log('total', num);
				return num;
			}
			return 0;
		},
		/* 满减信息*/
		couponInfo() {
			let list = [],
				index = 0,
				total = 0;
			if (this.coupon_deduction.type == 1) {
				/* 满减金额 */
				list = this.coupon_deduction.amount_deduction || [];
				total = this.totalPrice;
			} else {
				list = this.coupon_deduction.qty_deduction || [];
				total = this.totalGoodsNum;
			}
			console.log('list', list, total);
			if (total > 0) {
				list.forEach((subitem, subindex) => {
					if (subitem[0] <= total) {
						index = subindex + 1;
					}
				});
			}
			return index >= 0 && index < list.length
				? {
						index,
						total: list[index][0],
						money: list[index][1]
				  }
				: {
						index
				  };
		},
		/* 还需要购买的数量或者金额 */
		needMoreNum() {
			if (this.coupon_deduction.status == 1 && this.couponInfo && this.couponInfo.index >= 0) {
				if (this.coupon_deduction.type == 1) {
					return this.couponInfo.total - this.totalPrice > 0 ? (this.couponInfo.total - this.totalPrice).toFixed(2) : 0;
				} else {
					return this.couponInfo.total - this.totalGoodsNum > 0 ? (this.couponInfo.total - this.totalGoodsNum).toFixed(0) : 0;
				}
			} else {
				return 0;
			}
		},
		/* 优惠金额 */
		couponMoney() {
			if (this.coupon_deduction.status == 1 && this.couponInfo && this.couponInfo.index >= 0) {
				return this.couponInfo.money || 0;
			} else {
				return 0;
			}
		},
		/* 已减金额 */
		reduceMoney() {
			if (this.coupon_deduction.status == 1 && this.couponInfo && this.couponInfo.index > 0) {
				let list = [];
				if (this.coupon_deduction.type == 1) {
					/* 满减金额 */
					list = this.coupon_deduction.amount_deduction;
				} else {
					list = this.coupon_deduction.qty_deduction;
				}
				return list[this.couponInfo.index - 1][1];
			}
			return 0;
		},
		/* 支付金额 */
		payMoney() {
			if (this.coupon_deduction.status == 1 && this.couponInfo && this.couponInfo.index > 0) {
				return (this.totalPrice - this.reduceMoney).toFixed(2);
			}
			return this.totalPrice;
		}
	},
	watch: {
		isLogin(newV, oldV) {
			if (newV && this.isInit) {
				this.upCallback();
			}
		}
	},
	mounted() {},
	methods: {
		...mapMutations(['setCartNum']),
		...mapActions(['getCarCount']),
		/*上拉加载的回调*/
		upCallback() {
			this.ids = '';
			this.isInit = true;
			if (this.isLogin) {
				this.getCarList();
				this.getCarCount();
			} else {
				this.mescroll.endBySize(0, 0);
			}
		},
		downCallback() {
			this.mescroll.resetUpScroll();
		},
		getCarList() {
			this.$postAction(this.$api.getCarList, null, {
				custom: {
					ShowLoading: false
				}
			})
				.then(da => {
					let curPageData = [];
					this.invalidCart = {};
					let invalidCartCount = 0;
					if (da.data.isArray && da.data.length == 0) {
						this.cartList = [];
						this.mescroll.endSuccess(curPageData.length, false);
						return false;
					}
					for (var key in da.data) {
						if (key != 'lose') {
							curPageData.push(da.data[key]);
						} else {
							invalidCartCount = da.data[key].count;
							this.invalidCart = da.data[key].data;
						}
					}
					if (this.mescroll.num == 1) this.cartList = []; //如果是第一页需手动制空列表
					console.log('curPageData', curPageData);
					if (curPageData && curPageData.length > 0) {
						curPageData.forEach(item => {
							item.checked = true;
							item.data.forEach(goods => {
								goods.checked = true;
							});
						});
						console.log('curPageData', curPageData);
						this.mescroll.endBySize(curPageData.length, curPageData.length);
						this.cartList = this.cartList.concat(curPageData); //追加新数据
					} else {
						this.mescroll.endBySize(invalidCartCount, invalidCartCount);
					}
					// this.countTotal();
				})
				.catch(() => {
					//联网失败, 结束加载
					this.mescroll.endErr();
				});
		},
		changCart(e) {
			let shop = this.cartList[e.idx];
			let goods = shop.data[e.index];
			goods.qty = e.num;
			shop.data[e.index] = { ...goods };
			if (e.num == 0) {
				this.downCallback();
			} else {
				this.$set(this.cartList, e.idx, shop);
			}
		},
		selectedAll() {
			let flag = this.checkAll;
			this.cartList.length > 0 &&
				this.cartList.forEach(item => {
					item.checked = !flag;
					item.data.forEach(goods => {
						goods.checked = !flag;
					});
				});
		},
		//批量删除购物车
		banchDel(type) {
			let selCartIds = [];
			let title = '';
			if (type == '1') {
				this.cartList.forEach(shop => {
					shop.data.forEach(good => {
						if (good.checked) {
							selCartIds.push(good.id);
						}
					});
				});
				title = '确认将这' + selCartIds.length + '个宝贝删除？';
			} else {
				title = '确认清空失效的宝贝吗？';
				selCartIds = this.invalidCart.map(good => good.id);
			}

			var param = {
				id: selCartIds.toString()
			};

			if (selCartIds.length == 0) {
				uni.showToast({
					title: '您还没有选择宝贝哦！',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			var $me = this;
			uni.showModal({
				title: '',
				content: title,
				success: function (res) {
					if (res.confirm) {
						$me.$postAction($me.$api.deleteCar, param).then(da => {
							if (da.code == 0) {
								$me.getCarList();
								$me.getCarCount();
							}
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//去下单
		toOrder() {
			var ids = [];
			this.cartList.forEach(shop => {
				shop.data.forEach(good => {
					if (good.checked) {
						ids.push(good.id);
					}
				});
			});
			if (ids.length == 0) {
				uni.showToast({
					title: '请选择至少一个产品下单！',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			this.ids = ids.join(',');
			if (this.sysInfo.home_set.is_tc == 1) {
				this.showModal = true;
			} else {
				this.calcOrder(this.ids);
			}
		},
		calcOrder(ids) {
			this.$postAction(
				this.$api.calcOrder,
				{
					goodsList: ids,
					transport: 0
				},
				{
					custom: {
						loading: true
					}
				}
			).then(da => {
				if (da.code == 0) {
					uni.navigateTo({
						url: '/pages/submitOrder/submitOrder?ids=' + ids
					});
				}
			});
		},
		emptyClick() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		changeShopAll(e) {
			let shop = this.cartList[e.index];
			shop.checked = !e.state;
			shop.data.forEach(goods => {
				goods.checked = !e.state;
			});
			this.$set(this.cartList, e.index, shop);
		},
		changeShopOne(e) {
			let shop = this.cartList[e.idx];
			let goods = shop.data[e.index];
			goods.checked = !e.state;
			shop.data[e.index] = { ...goods };
			shop.checked = shop.data.every(item => item.checked);
			this.$set(this.cartList, e.idx, shop);
		},
		confirmOrder() {
			this.calcOrder(this.ids);
			this.showModal = false;
		}
	}
};
</script>

<style lang="scss">
.top-warp {
	z-index: 9990;
	position: fixed;
	top: 0;
	/* css变量 */
	left: 0;
	width: 100%;
}
.content {
	padding: 26upx 28upx;
	color: #48484a;
	line-height: 48upx;
	font-size: 24upx;
}

.u-button--normal {
	height: 77upx !important;
	width: 200upx !important;
}
.carbar {
	position: fixed;
	bottom: 0;
	right: 0;
	left: 0;
	// padding: 20upx 28upx 20upx 56upx;
	z-index: 999;
	.tip {
		padding: 15upx 30upx;
		background: #f8e7d7;
		color: #000;
	}
	.paybar {
		height: 110upx;
		padding: 0 28upx 0 56rpx;
	}
	.price {
		color: var(--nav-bg);
		font-weight: 500;
		font-size: 32upx;
		margin-right: 24upx;
		.unit {
			font-size: 22upx;
		}
	}
}
</style>
